<template>
  <div class="container" style="margin: 10px">
    <el-card v-loading="loading" >
      <!-- 表单 -->
      <el-form label-width="70px" :inline="true" :model="form">
        <el-form-item label="关键字">
          <el-input v-model="form.keyword" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.state">
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handelClear">清除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelSearch">搜索</el-button>
        </el-form-item>
        <el-form-item class="filter-item fr">
          <el-button
            size="small"
            type="success"
            icon="el-icon-edit"
            @click="handelAdd"
            >新增技巧</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 数据记录 -->
      <el-alert
        v-if="alertText !== ''"
        :title="alertText"
        type="info"
        class="alert"
        :closable="false"
        show-icon
      ></el-alert>
      <template>
        <!-- 表格 -->
        <el-table :data="articlesList" style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            :index="indexFn"
          >
          </el-table-column>
          <el-table-column prop="title" label="文章标题" min-width="200">
            <template #default="{ row }">
              <div>
                {{ row.title }}
                <el-icon
                  class="el-icon-film"
                  style="color: blue"
                  v-if="row.videoURL"
                  @click.native="isVideoShow(row)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数"> </el-table-column>
          <el-table-column prop="creatorID" :formatter="formatterName" label="录入人"> </el-table-column>
          <el-table-column
            prop="createTime"
            label="录入时间"
            :formatter="formatterDate"
          >
          </el-table-column>
          <el-table-column prop="state" label="状态" :formatter="formatterSta" width="50">
          </el-table-column>
          <el-table-column label="操作" width="200px">
            <template #default="{ row }">
              <el-button type="text" @click="handelView(row.id)"
                >预览</el-button
              >
              <el-button type="text" @click="changeState(row)" ref="btn">{{
                row.state === 1 ? "已禁用" : "已启用"
              }}</el-button>
              <el-button
                type="text"
                :disabled="row.state === 0"
                @click="handelEditArt(row.id)"
                >修改</el-button
              >
              <el-button
                type="text"
                :disabled="row.state === 0"
                @click="handelDelArt(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页组件 -->
      <div
        class="pages"
        style=" margin-top: 20px"
      >
        <el-pagination
          style="text-align: right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :total="total"
          :page-size="pagesize"
          :page-sizes="[5, 10, 20, 30, 50]"
          background
          layout="prev, pager, next,sizes, jumper"
        ></el-pagination>
      </div>
      <!-- 添加弹框 -->
      <div class="container">
        <el-dialog
          :title="titleFn"
          :visible="showDialog"
          width="30%"
          @close="handelClose"
        >
          <el-form :model="addForm" :rules="rules" ref="addForm">
            <el-form-item prop="title" label="文章标题:">
              <el-input
                placeholder="请输入文章标题"
                v-model="addForm.title"
                style="width: 80%"
              />
            </el-form-item>
            <el-form-item prop="articleBody" label="文章内容:">
              <div style="margin-left: 80px">
                <!-- 富文本编辑器 -->
                <quillEditor
                  ref="myQuillEditor"
                  v-model="addForm.articleBody"
                  :options="editorOption"
                  style="height: 150px"
                >
                </quillEditor>
              </div>
            </el-form-item>
            <el-form-item label="视频地址:" style="margin-top: 80px">
              <el-input v-model="addForm.videoURL" style="width: 84%" />
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showDialog = false">取 消</el-button>
            <el-button type="primary" @click="handelSubmit">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 视频播放器 -->
      <div class="box" v-if="videoShow">
        <div class="close" @click="videoShow = false">
          <el-icon class="el-icon-close" />
        </div>
        <div class="video">
          <video controls autoplay width="800px">
            <source :src="url" type="video/mp4" />
          </video>
        </div>
      </div>
      <!-- 预览弹框 -->
      <div class="container">
        <el-dialog
        v-loading="viewLoading"
          title="预览文章"
          :visible="viewShowDialog"
          width="50%"
          @close="handelViewClose"
        >
        <h3>{{addForm.title}}</h3>
        <div style="border-bottom: dashed #cccccc;padding-bottom:10px;">
          <span >{{addForm.createTime |formatDate}}</span>
          <span style="margin-left:10px;">{{addForm.creatorID |formatName(userList)}}</span>
        <el-icon style="margin-left:10px;" class="el-icon-view"/>
        <span style="margin-left:10px;">{{addForm.visits}}</span>
        </div>
        <div style="padding:10px;background-color: #f5f5f5;">
          <span v-html="addForm.articleBody" />
        </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { status } from '@/api/hmmm/constants.js'
import {
  list,
  add,
  detail,
  update,
  remove,
  changeState
} from '@/api/hmmm/articles.js'
import dayjs from 'dayjs'
import { simple } from '@/api/base/users.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      status, // 状态
      form: {
        state: '',
        keyword: ''
      },
      page: 1, // 当前页
      pagesize: 10, // 每页条数
      total: 0, // 总条数
      articlesList: [], // 文章列表
      videoShow: false, // 弹框
      addForm: {
        // 新增 弹框表单
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 校验规则
      rules: {
        title: [
          { required: true, message: '文章标题不能为空!', trigger: blur }
        ],
        articleBody: [
          { required: true, message: '文章内容不能为空!', trigger: blur }
        ]
      },
      showDialog: false,
      loading: false, // 加载圈
      url: '',
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link'] // 链接、图片、视频-
          ]
        }
      },
      viewShowDialog: false, // 控制预览弹框显示
      userList: [], // 用户列表
      viewLoading: false
    }
  },
  computed: {
    // 记录条数
    alertText () {
      return `数据一共${this.total}条`
    },
    titleFn () {
      return this.addForm.id ? '修改文章' : '新增文章'
    }
  },
  methods: {
    // 1.点击清除按钮
    handelClear () {
      this.form = {}
    },
    // 2.点击搜索 根据输入框的值筛选数据进行渲染
    // bug 当跳转到第二页是没有筛选
    async handelSearch () {
      const obj = {}
      for (const key in this.form) {
        if (this.form[key] !== '') {
          obj[key] = this.form[key]
        }
      }
      const {
        data: { items }
      } = await list({ ...obj })
      this.articlesList = items
      this.page = 1
    },
    // 3.获取文章列表
    async getArticlesList () {
      this.loading = true
      const {
        data: { items, counts }
      } = await list({ page: this.page, pagesize: this.pagesize })
      this.loading = false
      this.articlesList = items
      console.log(items, 11111)
      this.total = counts
    },
    // 4.处理表格日期格式
    formatterDate (cellValue) {
      return dayjs(cellValue.addDate).format('YYYY-MM-DD HH:mm:ss')
    },
    // 5.处理状态格式
    formatterSta (cellValue) {
      const obj = status.find((item) => item.value === cellValue.state)
      return obj.label
    },
    // 8.监听页数的变化
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      this.getArticlesList()
    },
    // 7.监听当前页的变化
    handleCurrentChange (val) {
      const oldPage = this.page
      if (oldPage) {
        // 当前页码为空时
        if (oldPage !== val && val <= this.total) {
          // 当页面发生变化时或者大于等于总页数 更新当前页码
          this.page = val
          this.getArticlesList()
        }
      }
    },
    // 8.自定义排序
    indexFn (index) {
      return index + 1 + this.pagesize * (this.page - 1)
    },
    // 9.控制按钮状态
    async changeState (row) {
      if (row.state === 1) {
        await changeState({ id: row.id, state: 0 })
        this.getArticlesList()
        this.$message.success('操作成功!')
      } else {
        await changeState({ id: row.id, state: 1 })
        this.getArticlesList()
        this.$message.success('操作成功!')
      }
    },
    // 10. 视频播放
    isVideoShow (row) {
      this.videoShow = true
      this.url = row.videoURL
    },
    // 11.新增文章
    async handelAdd () {
      this.showDialog = true
      // 获取学科列表
    },
    // 12.删除标签
    handelDelArt (id) {
      if (this.getArticlesList.length < 1) {
        this.page--
      }
      this.$confirm('此操作将永久删除改标签,是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        await remove({ id: id })
        this.getArticlesList()
        this.$message.success('删除成功!')
      })
    },
    // 13.关闭t弹框
    handelClose () {
      this.showDialog = false
      // 重置
      this.$refs.addForm.resetFields()
      this.addForm = {
        // 弹框表单
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },
    // 14.标签添加/修改
    handelSubmit () {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return
        if (this.addForm.id) {
          // 修改
          await update({ ...this.addForm })
          this.$message.success('修改成功!')
        } else {
          // 添加
          console.log(this.addForm, '888')
          await add({ ...this.addForm })
          this.$message.success('添加成功!')
        }
        this.getArticlesList()
        this.handelClose()
      })
    },
    // 15.文章修改
    async handelEditArt (id) {
      this.showDialog = true
      const { data } = await detail({ id })
      this.addForm = data
    },
    // 16.预览
    async handelView (id) {
      this.viewLoading = true
      this.viewShowDialog = true
      const { data } = await detail({ id })
      this.addForm = data
      this.viewLoading = false
    },
    // 17.关闭预览
    handelViewClose () {
      this.viewShowDialog = false
      this.addForm = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },
    // 18.获取用户列表
    // async getUserList () {
    //   const { data } = simple()
    //   this.userList = data
    // },
    // 19.处理姓名格式
    formatterName (cellValue) {
      console.log(cellValue, 777)
      const obj = this.userList.find(item => item.id === cellValue.creatorID)
      console.log(obj.username, 666)
      return obj.username
    }
  },
  async created () {
    // 1.进页面就获取列表
    this.getArticlesList()
    // 2. 键盘回车事件
    window.onkeydown = function (e) {
      if (e.keyword === 13) {
        this.handleCurrentChang()
      }
    }
    const { data } = await simple()
    this.userList = data
  }
}
</script>

<style scoped lang='scss'>
.box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  overflow: hidden;
  z-index: 9999;
  .close {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 30px;
    left: 50%;
    transform: translate(-50%);
    background: rgba(0, 0, 0, 0.4);
    box-shadow: 0 0 5px rgb(0 0 0 / 40%);
    border-radius: 50%;
    text-align: center;
    line-height: 50px;
    color: #fff;
    font-size: 20px;
  }
  .video {
    width: 800px;
    height: 600px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
